package com.dhcc.controller;

import com.dhcc.api.R;
import com.dhcc.dto.AddSysPosition;
import com.dhcc.dto.ResourceAllocation;
import com.dhcc.dto.UpdatePosition;
import com.dhcc.entity.ClientUser;
import com.dhcc.entity.SysDepartment;
import com.dhcc.entity.SysUserPosition;
import com.dhcc.entity.SysUserResource;
import com.dhcc.httpApiService.IdGeneratorService;
import com.dhcc.service.*;
import com.dhcc.utils.AuthUtil;
import com.dhcc.utils.ResourceTreeBuilder;
import com.dhcc.vo.SysClientResourceListTree;
import com.dhcc.vo.SysUserPositionVo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/userSystem/clientPosition")
public class SysUserPositionController {
    @Resource
    private SysUserPositionService sysUserPositionService;
    @Resource
    private SysUserDepartmentInstitutionService sysUserDepartmentInstitutionService;
    @Resource
    private IdGeneratorService idGeneratorService;
    @Resource
    private ClientUserService clientUserService;
    @Resource
    private ClientInstitutionRoleDepartmentPositionService clientInstitutionRoleDepartmentPositionService;
    @Resource
    private SysDepartmentService sysDepartmentService;
    @Resource
    private InstitutionRoleDepartmentPositionService institutionRoleDepartmentPositionService;
    @Resource
    private SysUserResourceService sysUserResourceService;
    /**
     * 通过机构编号，机构角色编号，部门编号查询岗位名称
     */
    @GetMapping("/getPositionNameList")
    public R<List<String>> getPositionNameList(String institutionId,String institutionRoleId,String departmentId){
        return R.data(sysUserPositionService.getPositionNameList(institutionId,institutionRoleId,departmentId));
    }
    /**
     * 查询当前机构下的岗位列表
     */
    @GetMapping("/selectPositionList")
    public R<List<SysUserPositionVo>> selectPositionList(String institutionId,String institutionRoleId){
        List<SysUserPositionVo> sysUserPositionList=new ArrayList<>();
        //查询岗位编号列表
        List<String> positionIds= sysUserDepartmentInstitutionService.selectPositionList(institutionId,institutionRoleId);
        for (String positionId : positionIds) {
            SysUserPosition position = sysUserPositionService.getPositionName(positionId);
            SysUserPositionVo sysUserPositionVo=new SysUserPositionVo();
            BeanUtils.copyProperties(position,sysUserPositionVo);
            String departmentId = clientInstitutionRoleDepartmentPositionService.selectDepartmentId(institutionId, institutionRoleId, positionId);
            //在部门表中查询部门名称
            SysDepartment department = sysDepartmentService.getDepatment(departmentId);
            if (department!=null){
                sysUserPositionVo.setDepartmentId(department.getDepartmentId());
                sysUserPositionVo.setDepartmentName(department.getDeptName());
            }

            sysUserPositionList.add(sysUserPositionVo);
        }
        return R.data(sysUserPositionList);
    }
    /**
     * 岗位新增
     */
    @PostMapping("/addPosition")
    @Transactional
    public R addPosition(@RequestBody AddSysPosition addSysPosition){
        SysUserPosition sysUserPosition=new AddSysPosition();
        BeanUtils.copyProperties(addSysPosition,sysUserPosition);
        Long aLong = idGeneratorService.nextId();
        sysUserPosition.setPositionId(aLong.toString());
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式化器，格式化为 "yyyy-MM-dd HH:mm:ss"
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = now.format(formatter);
        sysUserPosition.setCreateTime(format);
        String userId = AuthUtil.getUserId();
        //查询用户信息
        ClientUser user = clientUserService.getUserById(userId);
        sysUserPosition.setCreateUser(user.getName());
        //在岗位表添加数据
        Integer addPositionResult =sysUserPositionService.addPosition(sysUserPosition);
        if (addPositionResult!=1){
            throw new RuntimeException("岗位表数据添加失败");
        }
        //机构，机构角色，部门，岗位关联表中添加数据
        Integer insertResult= clientInstitutionRoleDepartmentPositionService.insertPositionInforment(addSysPosition.getInstitutionId(),addSysPosition.getInstitutionRoleId(),addSysPosition.getDepartmentId(),sysUserPosition.getPositionId());
        if (insertResult!=1){
            throw new RuntimeException("机构，机构角色，部门，岗位关联表中添加数据失败");
        }
        Integer integer = sysUserDepartmentInstitutionService.insertPositionInforment(addSysPosition.getInstitutionId(), addSysPosition.getInstitutionRoleId(), addSysPosition.getDepartmentId(), sysUserPosition.getPositionId());
        if (integer!=1){
            return R.fail("数据新增失败");
        }
        return R.success();
    }
    /**
     * 删除岗位信息
     */
    @GetMapping("/deletePosition")
    @Transactional
    public R deletePosition(String institutionId,String institutionRoleId,String departmentId,String positionId){
        //删除岗位表中的数据
        Integer deletePositionResult= sysUserPositionService.deletePosition(positionId);
        if (deletePositionResult!=1){
            throw new RuntimeException("岗位表数据删除异常");
        }
        //删除关联表中的信息
        Integer deleteResult=clientInstitutionRoleDepartmentPositionService.delete(institutionId,institutionRoleId,departmentId,positionId);
        if (deleteResult!=1){
            throw new RuntimeException("关联表数据删除失败");
        }
        Integer result= sysUserDepartmentInstitutionService.deleteData(institutionId,institutionRoleId,departmentId,positionId);
        if (result!=1){
            return R.fail("删除失败");
        }
        return R.success();
    }
    /**
     * 查询岗位信息
     */
    @GetMapping("/selectPositionInfo")
    public R<SysUserPositionVo> selectPositionInfo(String institutionId,String institutionRoleId,String positionId){
        SysUserPositionVo sysUserPositionVo=new SysUserPositionVo();
        SysUserPosition sysUserPosition=sysUserPositionService.getPositionName(positionId);
        BeanUtils.copyProperties(sysUserPosition,sysUserPositionVo);
        //在关联表中查询上级机构编号
        String departmentId= clientInstitutionRoleDepartmentPositionService.selectDepartmentId(institutionId,institutionRoleId,positionId);
        //在部门表中查询部门名称
        SysDepartment department = sysDepartmentService.getDepatment(departmentId);
        if (department!=null){
            sysUserPositionVo.setDepartmentName(department.getDeptName());
            sysUserPositionVo.setDepartmentId(department.getDepartmentId());
        }
        return R.data(sysUserPositionVo);
    }
    /**
     * 修改岗位信息
     */
    @PostMapping("/updatePosition")
    @Transactional
    public R updatePosition(@RequestBody UpdatePosition updatePosition){
        SysUserPosition sysUserPosition=new SysUserPosition();
        BeanUtils.copyProperties(updatePosition,sysUserPosition);
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式化器，格式化为 "yyyy-MM-dd HH:mm:ss"
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = now.format(formatter);
        sysUserPosition.setUpdateTime(format);
        String userId = AuthUtil.getUserId();
        //查询用户信息
        ClientUser user = clientUserService.getUserById(userId);
        sysUserPosition.setUpdateUser(user.getName());
        //修改岗位信息
        Integer updateResult= sysUserPositionService.updatePosition(sysUserPosition);
        if (updateResult!=1){
            throw new RuntimeException("岗位信息更新失败");
        }
        //修改关联表中的信息
        Integer result= clientInstitutionRoleDepartmentPositionService.updateDepartmentId(updatePosition.getDepartmentId(),updatePosition.getInstitutionId(),updatePosition.getInstitutionRoleId(),updatePosition.getPositionId());
        if (result!=1){
            throw new RuntimeException("关联表修改失败");
        }
        return R.success();
    }

    /**
     * 资源分配
     */
    @PostMapping("/resourceAllocation")
    @Transactional
    public R resourceAllocation(@RequestBody ResourceAllocation resourceAllocation ){
        //删除当前机构下部门下的所有资源关联数据
        Integer delResult= institutionRoleDepartmentPositionService.delData(resourceAllocation.getInstitutionId(),resourceAllocation.getInstitutionRoleId(),resourceAllocation.getDepartmentId(),resourceAllocation.getPositionId());
        if (delResult<=0){
            throw new RuntimeException("关联数据删除失败");
        }
        //添加关联数据
        for (String resourceId : resourceAllocation.getResourceIdList()) {
            Integer integer = institutionRoleDepartmentPositionService.addData(resourceAllocation.getInstitutionId(), resourceAllocation.getInstitutionRoleId(), resourceAllocation.getDepartmentId(), resourceAllocation.getPositionId(), resourceId);
            if (integer<1){
                throw new RuntimeException("数据添加失败");
            }
        }
        return R.success();

    }
    /**
     * 查询所有的资源列表
     */
    @GetMapping("/getAllResourceList")
    public R<List<SysClientResourceListTree>> getAllResourceList(){
            List<SysUserResource> SysUserResourceList= sysUserResourceService.getAllResourceList();
        return R.data(ResourceTreeBuilder.buildResourceTree(SysUserResourceList,null));
    }
    /**
     * 查询已分配的资源编号列表
     */
    @GetMapping("/getAlreadyAllocationResourceIds")
    public R<List<String>> getAlreadyAllocationResourceIds(String institutionId,String institutionRoleId,String departmentId,String positionId){
        List<String> resourceIds=institutionRoleDepartmentPositionService.getResourceIds(institutionId,institutionRoleId,departmentId,positionId);
        return R.data(resourceIds);
    }
}
